package main

import (
	"common/gateway"
	"common/modelrsa"
	"common/response"
	"common/utils"
	"context"
	"flag"
	"fmt"
	"gateway/internal/config"
	"gateway/internal/handler"
	"gateway/internal/middleware"
	"gateway/internal/svc"
	websocket2 "gateway/websocket"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"google.golang.org/grpc"
	"net/http"
	"os"
	adminpb "service/pb"
)

var env string

func main() {
	flag.Parse()

	if envEnv := os.Getenv("GO_ENV"); envEnv != "" {
		env = envEnv
	}

	if env == "" {
		env = "dev" // 默认使用开发环境
	}

	var configPath string
	switch env {
	case "dev":
		configPath = "etc/user-api-uat-local.yaml"
	case "uat":
		configPath = "etc/user-api-uat.yaml"
	case "prd":
		configPath = "etc/user-api-prd.yaml"
	default:
		fmt.Println("Unknown environment:", env)
		return
	}

	fmt.Println("configPat:", configPath)
	var configFile = flag.String("f", configPath, "the config file")
	var c config.Config
	conf.MustLoad(*configFile, &c)
	pr := utils.ReadFile("etc/PRIVATEKEY.pem")
	pu := utils.ReadFile("etc/PUBLICKEY.pem")
	modelrsa.SetUp(pr, pu)
	arminrpc := gateway.HeperFace{
		GrpcEndpoint: c.AdminRpcClientConf.Target,
		RegisterFuncs: []func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error){
			adminpb.RegisterSumHandlerFromEndpoint,
			adminpb.RegisterTestRpcHandlerFromEndpoint,
			adminpb.RegisterClassificationHandlerFromEndpoint,
			adminpb.RegisterGoodsHandlerFromEndpoint,
			adminpb.RegisterUsersHandlerFromEndpoint,
			adminpb.RegisterShopsHandlerFromEndpoint,
			adminpb.RegisterGoodsTemplateHandlerFromEndpoint,
		},
	}
	//filesRpc := gateway.HeperFace{
	//	GrpcEndpoint: c.FilesRpcClientConf.Target,
	//	RegisterFuncs: []func(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error){
	//		files.RegisterOssHandlerFromEndpoint,
	//	},
	//}
	adminGh, err := gateway.GrpcHandler(
		context.Background(),
		[]func(http.HandlerFunc) http.HandlerFunc{middleware.NewUserInfoMiddleware(c).Handle}, //middleware
		//[]gateway.HeperFace{arminrpc, filesRpc},
		[]gateway.HeperFace{arminrpc},
	)

	if err != nil {
		panic(err)
	}
	server := rest.MustNewServer(c.RestConf, rest.WithNotFoundHandler(adminGh), rest.WithUnauthorizedCallback(response.JwtUnauthorizedResult))
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	websocket2.RunStart(ctx.DB)
	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
